import re

import jwt
from django.http import HttpResponse
from django.shortcuts import redirect
from django.utils.deprecation import MiddlewareMixin
from rest_framework import exceptions

from rest_framework.exceptions import AuthenticationFailed
from rest_framework_jwt.serializers import VerifyJSONWebTokenSerializer
from rest_framework_jwt.utils import jwt_decode_handler
from users.models import User

from hw_booking_system.utils import TokenAuth


class JWTMiddleWare(MiddlewareMixin):
    def process_request(self, request):
        ip_addr = request.META['REMOTE_ADDR']
        # 获取请求路径
        path_info = request.path_info

        if not re.match('^/login', path_info):
            print(path_info)
            token = {"token": None}
            # print(request.META.get("HTTP_TOKEN"))
            token["token"] = request.META.get('HTTP_TOKEN')
            if token["token"] is None:
                # 跳转到登录界面
                return redirect("")
            try:
                # 校验user第2步：token => payload
                valid_data = jwt_decode_handler(token["token"])
            except jwt.ExpiredSignature:
                msg = 'Signature has expired.'
                raise exceptions.AuthenticationFailed(msg)
            except jwt.DecodeError:
                msg = 'Error decoding signature.'
                raise exceptions.AuthenticationFailed(msg)
            except jwt.InvalidTokenError:
                raise exceptions.AuthenticationFailed()
            user = valid_data['username']
            if user:
                v=User.objects.filter(username=user)
                if v.exists():
                    return
                else:
                    return redirect("")

        return
